package com.liu.jbase.service.impl;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.liu.jbase.BaseVo;
import com.liu.jbase.PageListVo;
import com.liu.jbase.ResultVo;
import com.liu.jbase.constant.ResCode;
import com.liu.jbase.service.IBaseService;
import com.liu.jbase.service.db.IDBBaseService;
import com.liu.jbase.util.AnnotationUtil;
import com.liu.tools.LogUtil;
import com.liu.tools.PrimaryUtil;

public class BaseServiceImpl<R, T, E extends IDBBaseService<R, T>> implements IBaseService<R, T>{

	private static Logger logger = LoggerFactory.getLogger(BaseServiceImpl.class);
	
	@Autowired
	private E dbService;
	
	@Override
	public ResultVo<R> deleteById(Serializable id, HttpServletRequest request) {
		
		ResultVo<R> res = new ResultVo<>();
		res.setCode(ResCode.FAIL);
		try {
			
			int flag = dbService.deleteById(id);
			
			if(flag > 0){
				res.setCode(ResCode.SUCCESS);
			}
			
		} catch (Exception e) {
			res.setCode(ResCode.EXCEPTION);
			logger.error(LogUtil.msg("BaseServiceImpl:deleteById", dbService.getClass().getName() + ", 删除记录异常"), e);
		}
		
		return res;
	}

	@Override
	public ResultVo<R> add(T record, HttpServletRequest request) {
		
		ResultVo<R> res = new ResultVo<>();
		res.setCode(ResCode.FAIL);
		
		try {
			
			List<Field> list = AnnotationUtil.getInstance().getAnnotationAutoValueField(record.getClass());
            for (Field field : list) {
                Object fieldValue = field.getDeclaringClass()
                        .getDeclaredMethod("get" + StringUtils.capitalize(field.getName())).invoke(record);
                if (fieldValue == null || StringUtils.isEmpty(fieldValue.toString())) {
                	if(field.getName().equals("createTime")){
                		field.getDeclaringClass()
                        .getDeclaredMethod("set" + StringUtils.capitalize(field.getName()), field.getType())
                        .invoke(record, new Date());
                	}
                	
                	if(field.getName().equals("updateTime")){
                		field.getDeclaringClass()
                        .getDeclaredMethod("set" + StringUtils.capitalize(field.getName()), field.getType())
                        .invoke(record, new Date());
                	}
                }
             }
             
            Field field = AnnotationUtil.getInstance().getAnnotationPrimaryField(record.getClass());
			if (field != null) {

				logger.info(LogUtil.msg("BaseServiceImpl:add", dbService.getClass().getName() + ", 生成id添加记录"));

	            // 判断主键是否有值
	            Object priObj = field.getDeclaringClass()
	                    .getDeclaredMethod("get" + StringUtils.capitalize(field.getName())).invoke(record);
	            if (priObj == null || StringUtils.isEmpty(priObj.toString())) {
	                field.getDeclaringClass()
	                        .getDeclaredMethod("set" + StringUtils.capitalize(field.getName()), field.getType())
	                        .invoke(record, PrimaryUtil.primaryId("I"));
	            }

	        }
			
			int flag = dbService.insert(record);
			
			if(flag > 0){
				res.setCode(ResCode.SUCCESS);
			}
			
		} catch (Exception e) {
			res.setCode(ResCode.EXCEPTION);
			logger.error(LogUtil.msg("BaseServiceImpl:add", dbService.getClass().getName() + ", 添加记录异常"), e);
		}
		
		return res;
	}
	

	@Override
	public ResultVo<R> update(T record, HttpServletRequest request) {
		
		ResultVo<R> res = new ResultVo<>();
		res.setCode(ResCode.FAIL);
		try {
			
			int flag = dbService.update(record);
			
			if(flag > 0){
				res.setCode(ResCode.SUCCESS);
			}
			
		} catch (Exception e) {
			res.setCode(ResCode.EXCEPTION);
			logger.error(LogUtil.msg("BaseServiceImpl:update", dbService.getClass().getName() + ", 更新记录异常"), e);
		}
		
		return res;
	}

	@Override
	public ResultVo<R> findById(Serializable id, HttpServletRequest request) {
		
		ResultVo<R> res = new ResultVo<>();
		res.setCode(ResCode.FAIL);
		try {
			
			R r = dbService.queryById(id);

			res.setCode(ResCode.SUCCESS);
			if(r == null){
				res.setCode(ResCode.DATA_NOT_EXSIT);
			}
			res.setData(r);
			
		} catch (Exception e) {
			res.setCode(ResCode.EXCEPTION);
			logger.error(LogUtil.msg("BaseServiceImpl:findById", dbService.getClass().getName() + ", 查询记录异常"), e);
		}
		
		return res;
	}

	@Override
	public ResultVo<R> find(T record, HttpServletRequest request) {
		ResultVo<R> res = new ResultVo<>();
		res.setCode(ResCode.FAIL);
		try {
			
			R r = dbService.query(record);

			res.setCode(ResCode.SUCCESS);
			if(r == null){
				res.setCode(ResCode.DATA_NOT_EXSIT);
			}
			res.setData(r);
			
		} catch (Exception e) {
			res.setCode(ResCode.EXCEPTION);
			logger.error(LogUtil.msg("BaseServiceImpl:find", dbService.getClass().getName() + ", 查询记录异常"), e);
		}
		
		return res;
	}

	@Override
	public ResultVo<List<R>> list(T record, HttpServletRequest request) {
		
		ResultVo<List<R>> res = new ResultVo<>();
		res.setCode(ResCode.FAIL);
		try {
			
			List<R> list = dbService.list(record);

			res.setCode(ResCode.SUCCESS);
			if (list == null) {
				res.setCode(ResCode.DATA_NOT_EXSIT);
			}
			res.setData(list);
			
		} catch (Exception e) {
			res.setCode(ResCode.EXCEPTION);
			logger.error(LogUtil.msg("BaseServiceImpl:list", dbService.getClass().getName() + ", 查询记录异常"), e);
		}
		
		return res;
	}

	@Override
	public ResultVo<PageListVo<R>> page(T record, PageListVo<R> page, HttpServletRequest request) {
		
		ResultVo<PageListVo<R>> res = new ResultVo<>();
		try {
			
			if(record != null){
				BaseVo baseVo = (BaseVo) record;
				if(baseVo.getCurPage() != null){
					page.setCurrPage(baseVo.getCurPage());
				}
				if(baseVo.getPageSize() != null){
					page.setPageSize(baseVo.getPageSize());
				}
			}
			

			PageListVo<R> pageListVo = dbService.page(record, page);
			res.setCode(ResCode.SUCCESS);
			res.setData(pageListVo);
			
		} catch (Exception e) {
			res.setCode(ResCode.EXCEPTION);
			logger.error(LogUtil.msg("BaseServiceImpl:page", dbService.getClass().getName() + ", 分页查询异常"), e);
		}
		return res;
	}

	@Override
	public ResultVo<R> delete(T record, HttpServletRequest request) {
		
		ResultVo<R> res = new ResultVo<>();
		res.setCode(ResCode.FAIL);
		try {
			
			int flag = dbService.delete(record);
			
			if(flag > 0){
				res.setCode(ResCode.SUCCESS);
			}
			
		} catch (Exception e) {
			res.setCode(ResCode.EXCEPTION);
			logger.error(LogUtil.msg("BaseServiceImpl:delete", dbService.getClass().getName() + ", 删除记录异常"), e);
		}
		
		return res;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ResultVo<R> count(T record, HttpServletRequest request) {
		
		ResultVo<R> res = new ResultVo<>();
		res.setCode(ResCode.FAIL);
		try {
			
			Long count = dbService.count(record);

			res.setCode(ResCode.SUCCESS);
			res.setData((R) count);
			
		} catch (Exception e) {
			res.setCode(ResCode.EXCEPTION);
			logger.error(LogUtil.msg("BaseServiceImpl:count", dbService.getClass().getName() + ", 统计数据异常"), e);
		}
		
		return res;
	}

}
